<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:chapter:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:chapter:edit']"
          >修改</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="chapterList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="章节名称" align="center" prop="name" />
      <el-table-column label="章节封面" align="center" prop="image">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.image"
            fit="cover"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="章节排序" align="center" prop="orderNum" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:chapter:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:chapter:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        label="文件管理"
        width="550"
        align="center"
        prop="id"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="small"
            type="success"
          >
            <router-link
              :to="
                '/steady/type/data/' +
                  scope.row.parentId +
                  '/' +
                  104 +
                  '/' +
                  scope.row.id
              "
              class="link-type"
              >视频管理</router-link
            ></el-button
          >
          <el-button size="small" type="info"
            ><router-link
              :to="
                '/steady/type/data/' +
                  scope.row.parentId +
                  '/' +
                  105 +
                  '/' +
                  scope.row.id
              "
              class="link-type"
              >拓展训练</router-link
            ></el-button
          >
          <el-button
            size="small"
            type="warning"
            ><router-link
              :to="
                '/steady/type/data/' +
                  scope.row.parentId +
                  '/' +
                  106 +
                  '/' +
                  scope.row.id
              "
              class="link-type"
              >老师教案</router-link
            ></el-button
          >
          <el-button
            size="small"
            type="danger"
            ><router-link
              :to="
                '/steady/type/data/' +
                  scope.row.parentId +
                  '/' +
                  107 +
                  '/' +
                  scope.row.id
              "
              class="link-type"
              >同步字帖</router-link
            ></el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改章节对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="章节名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入章节名称" />
        </el-form-item>
        <el-form-item label="章节封面" prop="image">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :headers="headers"
            :data="uploadData"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeAvatarUpload"
            name="file"
            :show-file-list="false"
            ref="upload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="显示排序" prop="orderNum">
          <el-input-number
            v-model="form.orderNum"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listChapter,
  getChapter,
  addChapter,
  updateChapter,
  delChapter
} from "@/api/chapter/chapter";
import { getToken } from "@/utils/auth";

export default {
  name: "steady",
  data() {
    return {
      // 上传的图片服务器地址
      uploadUrl: process.env.VUE_APP_BASE_API + "/system/upload/uploadFile",
      headers: {
        Authorization: "Bearer " + getToken()
      },
      uploadData: {
        type: "111"
      },
      imageUrl: "",
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 章节表格数据
      chapterList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        parentId: undefined,
        pageNum: 1,
        pageSize: 10,
        postCode: undefined,
        postName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "章节名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "章节顺序不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getDicts("course_management").then(response => {
      this.statusOptions = response.data;
      this.queryParams.parentId = response.data[2].dictCode;
      this.getList();
    });
  },
  methods: {
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      listChapter(this.queryParams).then(response => {
        this.chapterList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 岗位状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        parentId: this.queryParams.parentId,
        name: undefined,
        image: undefined,
        orderNum: undefined
      };
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.imageUrl = "";
      this.open = true;
      this.title = "添加岗位";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids;
      getChapter(id).then(response => {
        this.form = response.data;
        this.imageUrl = response.data.image;
        this.open = true;
        this.title = "修改章节";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateChapter(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addChapter(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(
        '是否确认删除章节名称为"' + row.name + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delChapter(row.id);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    handleUploadSuccess(res, file) {
      this.imageUrl = res.url;
      this.form.image = res.url;
    },
    handleUploadError() {
      this.$message.error("图片插入失败");
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    }
  }
};
</script>
<style scoped>
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
::v-deep .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-button span a {
  color: #ffffff;
}
</style>
